package com.dsg.controller.apply;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsg.aspect.NoRepeatSubmit;
import com.dsg.common.constants.MessageConstants;
import com.dsg.common.dto.AjaxResult;
import com.dsg.common.util.BeanKit;
import com.dsg.common.util.FileUtils;
import com.dsg.common.util.SingletonLoginUtils;
import com.dsg.common.util.UUIDGenerator;
import com.dsg.common.util.toolbox.CollectionUtil;
import com.dsg.common.util.toolbox.DateUtil;
import com.dsg.common.util.toolbox.StringUtil;
import com.dsg.controller.base.BaseController;
import com.dsg.entity.account.DsgAccountCard;
import com.dsg.entity.apply.*;
import com.dsg.entity.approve.DsgApproveCase;
import com.dsg.entity.dto.*;
import com.dsg.entity.oil.DsgOilCardStock;
import com.dsg.entity.system.DsgSysFile;
import com.dsg.service.account.IDsgAccountCardService;
import com.dsg.service.apply.*;
import com.dsg.service.approve.IDsgApproveCaseService;
import com.dsg.service.oil.IDsgOilCardStockService;
import com.dsg.service.system.IDsgSysFileService;
import com.dsg.util.Constant;
import com.dsg.util.FileUtil;
import com.dsg.workflow.AbstractWorkflowService;
import com.dsg.workflow.WorkflowEngine;
import com.dsg.workflow.WorkflowService3;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 油咭資料 前端控制器
 * </p>
 *
 * @author system
 * @since 2020-07-23
 */
@RestController
@RequestMapping("/apply/dsgApplyCard")
public class DsgApplyCardController extends BaseController {
    @Autowired
    IDsgApplyCardService service;
    @Autowired
    IDsgOilCardStockService stockService;
    @Autowired
    IDsgApplyBillService billService;
    @Autowired
    IDsgApplyStatusService statusService;
    @Autowired
    WorkflowEngine engine;
    @Autowired
    IDsgApproveCaseService caseService;
    @Autowired
    IDsgApplyCarService carService;
    @Autowired
    private IDsgSysFileService fileService;
    @Autowired
    IDsgApplyCusService cusService;
    @Autowired
    IDsgApplyDiscountService discountService;
    @Autowired
    IDsgApplyContactService contactService;
    @Autowired
    IDsgApplyPayService payService;
    @Autowired
    IDsgAccountCardService accountCardService;
    @Autowired
    IDsgApplyComService comService;

    @PutMapping(value = "/changeStatus")
    @ApiOperation("修改油咭密碼-更新")
    public AjaxResult changeStatus(@ApiParam(required = true) @RequestParam String oids,
                                   @ApiParam(required = true) @RequestParam Integer status) {
        if (DsgApplyBill.APP_STATUS_7 != status && DsgApplyBill.APP_STATUS_9 != status)
            return fail("更新的狀態不正確");
        LambdaUpdateWrapper<DsgApplyBill> wrapper = new LambdaUpdateWrapper<>();
        List<String> oidList = Arrays.asList(oids.split(","));
        wrapper.in(DsgApplyBill::getOid, oidList);
        DsgApplyBill bill = new DsgApplyBill();
        bill.setAppStatus(status);
        boolean res = billService.update(wrapper);
        if (!res)
            return fail("更新失敗");
        return success();
    }

    @GetMapping(value = "/getChangeCardList")
    @ApiOperation("修改油咭密碼-列表")
    @ApiResponses(
            @ApiResponse(response = ChangeCardDto.class, code = 0, message = "ok")
    )
    public AjaxResult getChangeCardList(ChangeCardDto dto) {
        dto.setEntCode(getEntCode());
        Page page = getPage();
        IPage<ChangeCardDto> iPage = service.selectChangeCard(page, dto);
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, iPage.getRecords(), (int) page.getTotal());
        return ajaxResult;
    }

    @GetMapping(value = "/printLetter")
    @ApiOperation("打印出咭信")
    public void printLetter(@ApiParam(required = true) @RequestParam String cardOid, HttpServletResponse response) throws Exception {
        DsgApplyCard card = service.getById(cardOid);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("CUS_NO", card.getCusNo());
        wrapper.eq("CUS_STATUS", DsgApplyCus.CUS_STATUS_1);
        DsgApplyCus cus = cusService.getOne(wrapper);
        DsgApplyCar car = carService.getById(card.getCarId());
        String enName;
        String cnName;
        if (cus != null) {
            enName = cus.getEnName();
            cnName = cus.getCnName();
        } else {
            wrapper = new QueryWrapper();
            wrapper.eq("COM_NO", card.getCusNo());
            wrapper.eq("CUS_STATUS", DsgApplyCus.CUS_STATUS_1);
            DsgApplyCom com = comService.getOne(wrapper);
            enName = com.getComEnName();
            cnName = com.getComCnName();
        }

        DsgApplyContact contact = contactService.getById(car.getCommId());
        String address = contact.getContactAddr();

        PdfReader reader = new PdfReader(FileUtils.getPdfTemplatePath("FC_出咭信_Template.pdf"));
        PdfStamper stamp = new PdfStamper(reader, response.getOutputStream());
        PdfContentByte over = stamp.getOverContent(1);
        over.beginText();

        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        over.setFontAndSize(bf, 12);
        over.showTextAligned(Element.ALIGN_LEFT, card.getCusNo(), 425, 690, 0);
        over.showTextAligned(Element.ALIGN_LEFT, car.getCarNo(), 425, 650, 0);
        over.showTextAligned(Element.ALIGN_LEFT, card.getCardNo(), 425, 610, 0);
        over.showTextAligned(Element.ALIGN_LEFT, enName, 50, 690, 0);
        over.showTextAligned(Element.ALIGN_LEFT, cnName, 50, 670, 0);
        over.showTextAligned(Element.ALIGN_LEFT, address, 50, 650, 0);
        over.endText();

        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-disposition", "attachment; filename=letter.pdf");
        stamp.close();
        reader.close();
    }

    @PostMapping(value = "/mapping")
    @ApiOperation("Caltex轉車牌mapping")
    public AjaxResult mapping(@ApiParam(required = true) @RequestParam String cardOid) {
        DsgApplyCard card = service.getById(cardOid);
        card.setCardStatus(DsgApplyCard.CARD_STATUS_4);
        service.updateById(card);
        return success();
    }

    @PutMapping(value = "/updatePre")
    @ApiOperation("更新即將返咭油咭編號")
    public AjaxResult updatePre(@RequestBody DsgApplyCard applyCard) {
        if (StringUtil.isEmpty(applyCard.getPreCardNo())) {
            return fail("预录入卡號不能为空");
        }
        service.updateById(applyCard);
        return success();
    }

    @GetMapping(value = "/{cardOid}/getCardDetail")
    @ApiOperation("油咭詳情")
    @ApiResponses(
            @ApiResponse(response = CardDetailDto.class, code = 0, message = "ok")
    )
    public AjaxResult getCardDetail(@PathVariable String cardOid) {
        DsgApplyCard card = service.getById(cardOid);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("CARD_ID", cardOid);
        wrapper.eq("DISCOUNT_TYPE", DsgApplyDiscount.DISCOUNT_TYPE_1);
        DsgApplyDiscount discount = discountService.getOne(wrapper);

        DsgApplyCar car = carService.getById(card.getCarId());

        wrapper = new QueryWrapper();
        wrapper.eq("APP_NO", card.getAppNo());
        DsgApplyBill bill = billService.getOne(wrapper);

        wrapper = new QueryWrapper();
        wrapper.eq("PID", bill.getCusId());
        wrapper.eq("CONTACT_TYPE", DsgApplyContact.CONTACT_TYPE_ADDRESS);
        List<DsgApplyContact> contactList = contactService.list(wrapper);

        wrapper = new QueryWrapper();
        wrapper.eq("MAIN_NO", bill.getMainNo());
        List<DsgApplyPay> payList = payService.list(wrapper);

        CardDetailDto dto = new CardDetailDto();
        dto.setBill(bill);
        dto.setCar(car);
        dto.setDiscount(discount);
        dto.setCard(card);
        dto.setContactList(contactList);
        dto.setPayList(payList);
        return success(dto);
    }

    @PostMapping(value = "/add")
    @ApiOperation("新增")
    public AjaxResult add(@RequestBody DsgApplyCard applyCard) {
        applyCard.setOid(UUIDGenerator.getUUID());
        boolean falg = service.save(applyCard);
        if (falg) {
            return result(MessageConstants.SSO_STATUS_SUCCESS);
        } else {
            return result(MessageConstants.SSO_STATUS_FAIL);
        }
    }

    @PutMapping(value = "/update")
    @ApiOperation("更新")
    public AjaxResult update(@RequestBody DsgApplyCard applyCard) {
        boolean flag = service.updateById(applyCard);
        if (flag) {
            return json(MessageConstants.SSO_STATUS_SUCCESS, applyCard);
        } else {
            return result(MessageConstants.SSO_STATUS_FAIL);
        }
    }

    @DeleteMapping(value = "/delete")
    @ApiOperation("删除")
    public AjaxResult delete(String id) {
        Boolean flag = service.removeById(id);
        if (flag) {
            return result(MessageConstants.SSO_STATUS_SUCCESS);
        } else {
            return result(MessageConstants.SSO_STATUS_FAIL);
        }
    }

    @GetMapping(value = "/{mainNo}/getByBill")
    @ApiOperation("查询单条数据")
    public AjaxResult getByBill(@PathVariable String mainNo) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("MAIN_NO", mainNo);
        DsgApplyCard applyCard = service.getOne(wrapper);
        return json(MessageConstants.SSO_STATUS_SUCCESS, applyCard);
    }

    @GetMapping(value = "/returnCard")
    @ApiOperation("FC返咭列表")
    @ApiResponses({
            @ApiResponse(response = ReturnCardDto.class, code = 1, message = "ok")
    })
    public AjaxResult returnCard(String cardNo, String cardFaceName, String carOilType, String carNo,String cardType,
                                 @ApiParam(name = "cardEndDate", required = true)@RequestParam("cardEndDate")String cardEndDate) {
        List<ReturnCardDto> list = service.selectReturnCard(AbstractWorkflowService.NODE_RETURN_CARD,null, null, carOilType, carNo, null, null, cardType);

        List<ReturnCardDto> tempList = list.stream().filter(e -> e.getIsReturn().equals(0) && StringUtil.isEmpty(e.getCardNo())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(tempList)) {
            tempList.forEach(e->e.setReturnType(1));//待返卡
            return json(MessageConstants.SSO_STATUS_SUCCESS, tempList);
        } else {
            tempList = list.stream().filter(e -> e.getIsReturn().equals(1) && cardEndDate.equals(e.getCardEndDate())
                    && cardNo.equals(e.getCardNo()) && cardFaceName.equals(e.getCardFaceName())).collect(Collectors.toList());
        }

        if (CollectionUtil.isNotEmpty(tempList)) {
            tempList.forEach(e->e.setReturnType(2));//已返卡
            return json(MessageConstants.SSO_STATUS_SUCCESS, tempList);
        } else {
            tempList = list.stream().filter(e -> !cardEndDate.equals(e.getCardEndDate())
                    && cardNo.equals(e.getCardNo())
                    && cardFaceName.equals(e.getCardFaceName())).collect(Collectors.toList());
        }

        if (CollectionUtil.isNotEmpty(tempList))
            tempList.forEach(e->e.setReturnType(3));//renew卡
        return json(MessageConstants.SSO_STATUS_SUCCESS, tempList);
    }

    @PostMapping(value = "/bindCard")
    @ApiOperation("绑定卡")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult bindCard(@ApiParam(required = true)@RequestParam String cardNo,
                               @ApiParam(required = true)@RequestParam String cardOid,
                               @ApiParam(required = true)@RequestParam String cardEndDate,
                               @ApiParam(required = true)@RequestParam String cardFaceName) throws Exception {
        List<String> cardNoList = Arrays.asList(cardNo.split(","));
        Set<String> set = new HashSet<>(cardNoList);
        if (set.size() != cardNoList.size())
            throw new Exception("卡號不能重覆");

        List<String> cardOidList = Arrays.asList(cardOid.split(","));
        List<String> cardEndDateList = Arrays.asList(cardEndDate.split(","));
        List<String> cardFaceNameList = Arrays.asList(cardFaceName.split(","));
        for (int i = 0; i < cardNoList.size(); i++) {
            String cardId = cardOidList.get(i);
            String cardNo1 = cardNoList.get(i);
            String cardEndDate1 = cardEndDateList.get(i);
            String cardFaceName1 = cardFaceNameList.get(i);

            cardEndDate1 = String.format("20%s01", cardEndDate1);
            Date date = DateUtil.parseDate(cardEndDate1, "yyyyMMdd");
            DsgApplyCard card = service.getById(cardId);
            card.setCardNo(cardNo1);
            card.setCardEndDate(date);
            card.setCardFaceName(cardFaceName1);
            card.setCardInTime(new Date());
            card.setCardStatus(DsgApplyCard.CARD_STATUS_2);
            service.updateById(card);
            saveStockAndStatus(card);
            DsgApproveCase applyCase = caseService.getCase(WorkflowService3.NODE_RETURN_CARD, card.getAppNo());
            if (applyCase == null) {
                throw new Exception("无返卡CASE");
            }
            if (DsgApproveCase.Status.started.getCode().equals(applyCase.getStatus())) {
                engine.forward(applyCase);
            }
        }
        return success();
    }

    //2：該車的申請記錄變成“拒絕”（忽略這句話）
    @PostMapping(value = "/unbindCard")
    @ApiOperation("解除绑定卡")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult unbindCard(@ApiParam(required = true)@RequestParam String cardOid,
                                 @ApiParam(required = true)@RequestParam String cancelReason) throws Exception {
        DsgApplyCard card = service.getById(cardOid);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("APP_NO", card.getAppNo());
        wrapper.eq("CARD_ID", card.getOid());
        DsgApplyStatus status = statusService.getOne(wrapper);
        if (status.getIsSend() == 1) {
            throw new Exception("已發卡不能解除綁定");
        }
        status.setIsReturn(0);
        status.setCardNo(card.getCardNo());
        status.setCancelRea(cancelReason);
        statusService.updateById(status);

        String cardNo = card.getCardNo();
        LambdaUpdateWrapper<DsgApplyCard> updateWrapper2 = new LambdaUpdateWrapper();
        updateWrapper2.set(DsgApplyCard::getCardNo, null);
        updateWrapper2.set(DsgApplyCard::getCardEndDate, null);
        updateWrapper2.set(DsgApplyCard::getCardFaceName, null);
        updateWrapper2.eq(DsgApplyCard::getCardNo, cardNo);
        updateWrapper2.eq(DsgApplyCard::getCardInTime, null);
        updateWrapper2.eq(DsgApplyCard::getCardStatus, DsgApplyCard.CARD_STATUS_1);
        service.update(card, updateWrapper2);

        LambdaUpdateWrapper<DsgOilCardStock> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(DsgOilCardStock::getCardNo, cardNo);
        stockService.remove(updateWrapper);

//        if (true) throw new Exception("测试");//test
        return success();
    }

    @PutMapping(value = "/renewCard")
    @ApiOperation("renew咭")
    @ApiResponses({
            @ApiResponse(response = ReturnCardDto.class, code = 1, message = "ok")
    })
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult renewCard(List<RenewCardDto> list) throws Exception {
        for (RenewCardDto renewCardDto : list) {
            String cardOid = renewCardDto.getCardOid();
            String cardEndDate = renewCardDto.getCardEndDate();
            cardEndDate = String.format("20%s01", cardEndDate);
            Date date = DateUtil.parseDate(cardEndDate, "yyyyMMdd");
            DsgApplyCard card = service.getById(cardOid);
            card.setCardEndDate(date);
            service.updateById(card);

            DsgOilCardStock cardStock = new DsgOilCardStock();
            cardStock.setOid(UUIDGenerator.getUUID());
            cardStock.setAppNo(card.getAppNo());
            cardStock.setOilCom(card.getOilCom());
            cardStock.setCardClassify(card.getCardClassify());
            cardStock.setCardType(card.getCardType());
            cardStock.setCardNo(card.getCardNo());
            cardStock.setCardFaceName(card.getCardFaceName());
            cardStock.setStockStatus(DsgOilCardStock.STOCK_STATUS_IN);
            cardStock.setCardInTime(new Date());
            cardStock.setPeriodTime(date);
            stockService.save(cardStock);
        }
        return success();
    }

    @GetMapping(value = "/selectSendCard")
    @ApiOperation("查询派咭列表")
    @ApiResponses({
            @ApiResponse(response = ReturnCardDto.class, code = 1, message = "ok")
    })
    public AjaxResult selectSendCard(@ApiParam(required = true)@RequestParam String cardNo) throws Exception {
        String ownsId = service.getOwnsIdByCardNo(cardNo);
        if (ownsId == null) {
            return fail("該卡無對應客戶");
        }

        List<ReturnCardDto> list = service.selectReturnCard(AbstractWorkflowService.NODE_SEND_CARD, null, null, null, null, true, ownsId,null);

        return json(MessageConstants.SSO_STATUS_SUCCESS, list);
    }

    @PutMapping(value = "/sendCard")
    @ApiOperation("派咭")
    @ApiResponses({
            @ApiResponse(response = ReturnCardDto.class, code = 1, message = "ok")
    })
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult sendCard(@ApiParam(required = true)@RequestParam String cardOids) throws Exception {
        List<String> list = Arrays.asList(cardOids.split(","));

        for (int i = 0; i < list.size(); i++) {
            DsgApplyCard card = service.getById(list.get(i));
            DsgApproveCase applyCase = caseService.getCase(WorkflowService3.NODE_SEND_CARD, card.getAppNo());
            if (applyCase == null) {
                throw new Exception("卡號"+ card.getCardNo() +"无派卡CASE");
            }
            if (DsgApproveCase.Status.started.getCode().equals(applyCase.getStatus())) {
                engine.forward(applyCase);
            }
            card.setCardOutTime(new Date());
            card.setCardStatus(DsgApplyCard.CARD_STATUS_4);
            service.updateById(card);

            LambdaUpdateWrapper<DsgApplyStatus> updateWrapper = new LambdaUpdateWrapper();
            updateWrapper.eq(DsgApplyStatus::getCardId, card.getOid());
            DsgApplyStatus status = new DsgApplyStatus();
            status.setIsSend(1);
            statusService.update(status, updateWrapper);

            LambdaUpdateWrapper<DsgOilCardStock> updateWrapper1 = new LambdaUpdateWrapper();
            updateWrapper1.eq(DsgOilCardStock::getCardNo, card.getCardNo());
            updateWrapper1.eq(DsgOilCardStock::getAppNo, card.getAppNo());
            DsgOilCardStock stock = new DsgOilCardStock();
            stock.setCardOutTime(new Date());
            stock.setStockStatus(DsgOilCardStock.STOCK_STATUS_OUT);
            stockService.update(stock, updateWrapper1);
        }

        return success();
    }

    @PostMapping(value = "/replaceCard")
    @ApiOperation("補咭")
    @Transactional(rollbackFor = Exception.class)
    @NoRepeatSubmit
    public AjaxResult replaceCard(String cardId,
                                  @ApiParam(required = true)@RequestParam String carNo,
                                  @ApiParam(required = true)@RequestParam String mailAddr,
                                  @ApiParam(required = true)@RequestParam Boolean stopOld,
                                  @ApiParam(required = true)@RequestParam String remark) throws Exception {
        DsgApplyCard card = service.getById(cardId);

        if (DsgApplyCard.CARD_STATUS_4 != card.getCardStatus()) {
            return fail("只能選擇生效中的咭");
        }

        if (stopOld) {
            card.setCardStatus(DsgApplyCard.CARD_STATUS_5);
            service.updateById(card);
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("APP_NO", card.getAppNo());
        DsgApplyBill bill = billService.getOne(wrapper);

        bill.setAppStatus(DsgApplyBill.APP_STATUS_4);
        if (DsgApplyBill.KEEP_TYPE_CASH == bill.getKeepType()) {
            bill.setAppType(DsgApplyBill.APP_TYPE_28);
        } else {
            bill.setAppType(DsgApplyBill.APP_TYPE_9);
        }
        bill.setAppType(DsgApplyBill.APP_TYPE_9);
        BeanKit.resetCommonField(bill);
        bill.setPayType(Constant.PAY_TYPE_ATP);
        bill.setOid(UUIDGenerator.getUUID());
        String appNo = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        bill.setAppNo(appNo);
        bill.setMailAddr(mailAddr);
        bill.setRemark(remark);
        billService.save(bill);

        card.setOldCardId(cardId);
        card.setOid(UUIDGenerator.getUUID());
        card.setAppNo(appNo);
        card.setCardNo(null);
        card.setCardInTime(null);
        card.setCardOutTime(null);
        card.setCardEndDate(null);
        card.setCreater(null);
        card.setCreateTime(null);
        card.setUpdater(null);
        card.setUpdateTime(null);
        card.setCardStatus(DsgApplyCard.CARD_STATUS_APPLY);
        service.save(card);

        copyDiscount(cardId, card.getOid());

        DsgApplyStatus status = new DsgApplyStatus();
        status.setOid(UUIDGenerator.getUUID());
        status.setAppNo(appNo);
        status.setCardId(card.getOid());
        status.setAppType(DsgApplyBill.APP_TYPE_9);
        status.setCarNo(carNo);
        status.setIsEntry(1);
        statusService.save(status);

        engine.begin(bill);

        return success();
    }

    private void copyDiscount(String oldCardId, String cardOid) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("CARD_ID", oldCardId);
        List<DsgApplyDiscount> discountList = discountService.list(wrapper);
        if (CollectionUtil.isNotEmpty(discountList)) {
            for (DsgApplyDiscount discount:discountList) {
                discount.setOid(UUIDGenerator.getUUID());
                discount.setCardId(cardOid);
                discount.setCreater(null);
                discount.setCreateTime(null);
                discount.setUpdater(null);
                discount.setUpdateTime(null);
            }
            discountService.saveBatch(discountList);
        }
    }

    @PostMapping(value = "/cancelCard")
    @ApiOperation("取消油咭")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult cancelCard(@ApiParam(name = "cardId", required = true)@RequestParam String cardId
            ,@ApiParam(required = true)@RequestParam String remark
            ,@ApiParam(required = true)@RequestParam String carNo
            ,@ApiParam(value = "其它附件类型", name = "otherType")@RequestParam(required = false) String otherType
    ,@ApiParam(name = "files", required = true)@RequestParam("files") MultipartFile[] files
    ) throws Exception {
        DsgApplyCard card = service.getById(cardId);
        if (DsgApplyCard.CARD_STATUS_4 != card.getCardStatus()) {
            return fail("只能選擇生效中的咭");
        }
        if (StringUtil.isEmpty(card.getCardNo())) {
            return fail("油咭號不能為空");
        }
        if (StringUtil.isEmpty(carNo)) {
            return fail("車牌號不能為空");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("MAIN_NO", card.getAppNo());
        wrapper.eq("APP_NO", card.getAppNo());
        DsgApplyBill bill = billService.getOne(wrapper);

        bill.setAppStatus(DsgApplyBill.APP_STATUS_4);
        if (DsgApplyBill.KEEP_TYPE_CASH == bill.getKeepType()) {
            bill.setAppType(DsgApplyBill.APP_TYPE_29);
        } else {
            bill.setAppType(DsgApplyBill.APP_TYPE_11);
        }
        bill.setCreateTime(null);
        bill.setOid(UUIDGenerator.getUUID());
        String appNo = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        bill.setAppNo(appNo);
        bill.setRemark(remark);
        billService.save(bill);

        DsgApplyStatus status = new DsgApplyStatus();
        status.setOid(UUIDGenerator.getUUID());
        status.setAppNo(appNo);
        status.setCardId(card.getOid());
        status.setAppType(DsgApplyBill.APP_TYPE_11);
        status.setCarNo(carNo);
        status.setIsEntry(1);
        statusService.save(status);

        MultipartFile applyFile = files[0];
        String fileName = applyFile.getOriginalFilename();
        String fileType = fileName.split("\\.")[1];
        File f = FileUtil.multipartToFile(applyFile);
        DsgSysFile sysFile = new DsgSysFile();
        sysFile.setAppNo(bill.getAppNo());
        sysFile.setEnclType(DsgSysFile.ENCL_TYPE_10);
        fileService.saveFile(sysFile, f, bill.getOid(), fileType);

        if (files.length >1) {
            MultipartFile otherFile = files[1];
            fileName = applyFile.getOriginalFilename();
            fileType = fileName.split("\\.")[1];
            f = FileUtil.multipartToFile(otherFile);
            sysFile.setOid(UUIDGenerator.getUUID());
            sysFile.setEnclType(otherType);
            fileService.saveFile(sysFile, f, bill.getOid(), fileType);
        }

        engine.begin(bill);
        return success(bill);
    }

    @PostMapping(value = "/stopCard")
    @ApiOperation("停咭")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult stopCard(String cardId, String carNo, String remark) throws Exception {
        DsgApplyCard card = service.getById(cardId);
        if (DsgApplyCard.CARD_STATUS_4 != card.getCardStatus()) {
            return fail("只能選擇生效中的咭");
        }
        if (StringUtil.isEmpty(card.getCardNo())) {
            return fail("油咭號不能為空");
        }
        if (StringUtil.isEmpty(carNo)) {
            return fail("車牌號不能為空");
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("MAIN_NO", card.getAppNo());
        wrapper.eq("APP_NO", card.getAppNo());
        DsgApplyBill bill = billService.getOne(wrapper);

        bill.setAppStatus(DsgApplyBill.APP_STATUS_DRAFT);
        bill.setAppType(DsgApplyBill.APP_TYPE_10);
        bill.setCreateTime(null);
        bill.setApplyTime(new Date());
        bill.setOid(UUIDGenerator.getUUID());
        String appNo = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        bill.setAppNo(appNo);
        bill.setRemark(remark);
        bill.setPayType(Constant.PAY_TYPE_ATP);
        billService.save(bill);

        DsgApplyStatus status = new DsgApplyStatus();
        status.setOid(UUIDGenerator.getUUID());
        status.setAppNo(appNo);
        status.setCardId(card.getOid());
        status.setAppType(DsgApplyBill.APP_TYPE_10);
        status.setCarNo(carNo);
        status.setIsEntry(1);
        statusService.save(status);

        wrapper = new QueryWrapper();
        wrapper.eq("CARD_NO", card.getCardNo());
        DsgAccountCard accountCard = accountCardService.getOne(wrapper);
        if (accountCard != null && accountCard.getArrearsValue().compareTo(BigDecimal.ZERO) > 0) {
            engine.begin(bill);
        } else {
            card.setCardStatus(DsgApplyCard.CARD_STATUS_7);
            service.updateById(card);
            bill.setAppStatus(DsgApplyBill.APP_STATUS_4);
            billService.updateById(bill);
        }
//        if (true) throw new Exception("测试");//test
        return success();
    }

    @PostMapping(value = "/openCard")
    @ApiOperation("開咭")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult openCard(String cardId, String carNo, String remark) throws Exception {
        DsgApplyCard card = service.getById(cardId);
        if (DsgApplyCard.CARD_STATUS_7 != card.getCardStatus()) {
            return fail("只有停咭狀態的咭才能開咭");
        }
        if (StringUtil.isEmpty(card.getCardNo())) {
            return fail("油咭號不能為空");
        }
        if (StringUtil.isEmpty(carNo)) {
            return fail("車牌號不能為空");
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("MAIN_NO", card.getAppNo());
        wrapper.eq("APP_NO", card.getAppNo());
        DsgApplyBill bill = billService.getOne(wrapper);

        bill.setAppStatus(DsgApplyBill.APP_STATUS_DRAFT);
        bill.setAppType(DsgApplyBill.APP_TYPE_8);
        bill.setCreateTime(null);
        bill.setOid(UUIDGenerator.getUUID());
        String appNo = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        bill.setAppNo(appNo);
        bill.setRemark(remark);
        bill.setPayType(Constant.PAY_TYPE_ATP);
        billService.save(bill);

        DsgApplyStatus status = new DsgApplyStatus();
        status.setOid(UUIDGenerator.getUUID());
        status.setAppNo(appNo);
        status.setCardId(card.getOid());
        status.setAppType(DsgApplyBill.APP_TYPE_8);
        status.setCarNo(carNo);
        status.setIsEntry(1);
        statusService.save(status);

        engine.begin(bill);
//        if (true) throw new Exception("测试");//test
        return success();
    }

    @GetMapping(value = "/selectCar")
    @ApiOperation("轉移油咭-查車列表")
    @Transactional(rollbackFor = Exception.class)
    @ApiResponses({
            @ApiResponse(response = DsgApplyCar.class, code = 1, message = "ok")
    })
    public AjaxResult selectCar(String cusNo) throws Exception {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("CUS_NO", cusNo);
        wrapper.isNotNull("CAR_NO");
        List<DsgApplyCar> carList = carService.selectCar(cusNo);
        if (CollectionUtil.isEmpty(carList))
            return fail("沒有車數據");
        for (DsgApplyCar car : carList) {
            wrapper = new QueryWrapper();
            wrapper.eq("CAR_ID", car.getOid());
            wrapper.eq("CARD_STATUS", DsgApplyCard.CARD_STATUS_4);
            List<DsgApplyCard> cardList = service.list(wrapper);
            if (CollectionUtil.isNotEmpty(cardList)) {
                car.setCardList(cardList);
            }
        }
        return success(carList);
    }

    @PostMapping(value = "/changeCardPassword")
    @ApiOperation("修改油咭密碼")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult changeCardPassword(String cardId, String carNo, String remark) throws Exception {
        DsgApplyCard card = service.getById(cardId);
        if (DsgApplyCard.CARD_STATUS_4 != card.getCardStatus()) {
            return fail("只能選擇生效中的咭");
        }
        if (StringUtil.isEmpty(card.getCardNo())) {
            return fail("油咭號不能為空");
        }
        if (StringUtil.isEmpty(carNo)) {
            return fail("車牌號不能為空");
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("MAIN_NO", card.getAppNo());
        wrapper.eq("APP_NO", card.getAppNo());
        DsgApplyBill bill = billService.getOne(wrapper);

        int appType = DsgApplyBill.APP_TYPE_14;
        bill.setAppStatus(DsgApplyBill.APP_STATUS_4);
        bill.setAppType(appType);
        bill.setCreateTime(null);
        bill.setOid(UUIDGenerator.getUUID());
        String appNo = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        bill.setAppNo(appNo);
        bill.setRemark(remark);
        bill.setPayType(Constant.PAY_TYPE_ATP);
        billService.save(bill);

        DsgApplyStatus status = new DsgApplyStatus();
        status.setOid(UUIDGenerator.getUUID());
        status.setAppNo(appNo);
        status.setCardId(card.getOid());
        status.setAppType(appType);
        status.setCarNo(carNo);
        status.setIsEntry(1);
        statusService.save(status);

        engine.begin(bill);
//        if (true) throw new Exception("测试");//test
        return success();
    }

    @PostMapping(value = "/replaceExpiredCard")
    @ApiOperation("過期補領")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult replaceExpiredCard(String cardId,
                                  String carNo,
                                  @ApiParam(required = true)@RequestParam String mailAddr,
                                  @ApiParam(required = true)@RequestParam String remark) throws Exception {
        DsgApplyCard card = service.getById(cardId);
        if (DsgApplyCard.CARD_STATUS_4 != card.getCardStatus()) {
            return fail("只能選擇生效中的咭");
        }
        if (StringUtil.isEmpty(card.getCardNo())) {
            return fail("油咭號不能為空");
        }
        if (StringUtil.isEmpty(carNo)) {
            return fail("車牌號不能為空");
        }
        if ((new Date()).compareTo(card.getCardEndDate()) < 0) {
            return fail("油咭未過期");
        }
        card.setCardStatus(DsgApplyCard.CARD_STATUS_8);
        service.updateById(card);

        QueryWrapper wrapper = new QueryWrapper();
//        wrapper.eq("MAIN_NO", card.getAppNo());
        wrapper.eq("APP_NO", card.getAppNo());
        DsgApplyBill bill = billService.getOne(wrapper);

        int appType = DsgApplyBill.APP_TYPE_13;
        bill.setAppStatus(DsgApplyBill.APP_STATUS_4);
        bill.setAppType(appType);
        bill.setCreateTime(null);
        bill.setOid(UUIDGenerator.getUUID());
        String appNo = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        bill.setAppNo(appNo);
        bill.setMailAddr(mailAddr);
        bill.setRemark(remark);
        bill.setPayType(Constant.PAY_TYPE_ATP);
        billService.save(bill);

        card.setOldCardId(cardId);
        card.setOid(UUIDGenerator.getUUID());
        card.setAppNo(appNo);
        card.setCreater(null);
        card.setCreateTime(null);
        card.setUpdater(null);
        card.setUpdateTime(null);
        card.setCardStatus(DsgApplyCard.CARD_STATUS_APPLY);
        card.setCardNo(null);
        service.save(card);

        copyDiscount(cardId, card.getOid());

        DsgApplyStatus status = new DsgApplyStatus();
        status.setOid(UUIDGenerator.getUUID());
        status.setAppNo(appNo);
        status.setCardId(card.getOid());
        status.setAppType(appType);
        status.setCarNo(carNo);
        status.setIsEntry(1);
        statusService.save(status);

        engine.begin(bill);
        DsgApproveCase approveCase = caseService.getCase(AbstractWorkflowService.NODE_CS_APPLY, bill.getAppNo());
        engine.forward(approveCase);

        return success();
    }

    @GetMapping(value = "/selectCardRecord")
    @ApiOperation("新咭返咭/派咭記錄")
    @ApiResponses(
            @ApiResponse(response = CardRecordDto.class, code = 0, message = "ok")
    )
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult selectCardRecord(Integer cardType, Integer appType, Integer cardStatus, Integer dedStatus) {
        List<CardRecordDto> list = service.selectCardRecord(cardType, appType, cardStatus, dedStatus, getEntCode());
        return success(list);
    }

    @PostMapping(value = "/bindCardSC")
    @ApiOperation("SC绑定卡")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult bindCardSC(@ApiParam(required = true)@RequestParam String cardOid,
                               @ApiParam(required = true)@RequestParam String cardEndDate) throws Exception {
        List<String> cardOidList = Arrays.asList(cardOid.split(","));
        List<String> cardEndDateList = Arrays.asList(cardEndDate.split(","));
        for (int i = 0; i < cardOidList.size(); i++) {
            String cardId = cardOidList.get(i);
            String cardEndDate1 = cardEndDateList.get(i);

            Date date = DateUtil.parseDate(cardEndDate1, "yyyy-MM-dd");
            DsgApplyCard card = service.getById(cardId);
            card.setCardEndDate(date);
            card.setCardInTime(new Date());
            card.setCardStatus(DsgApplyCard.CARD_STATUS_2);
            service.updateById(card);
            saveStockAndStatus(card);
            DsgApproveCase applyCase = caseService.getCase(WorkflowService3.NODE_RETURN_CARD, card.getAppNo());
            if (applyCase == null) {
                throw new Exception("无返卡CASE");
            }
            if (DsgApproveCase.Status.started.getCode().equals(applyCase.getStatus())) {
                engine.forward(applyCase);
            }
        }
        return success();
    }

    private void saveStockAndStatus(DsgApplyCard card) throws Exception {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("CARD_NO", card.getCardNo());
        if (stockService.count(wrapper) > 0)
            throw new Exception("庫存表存在相同的卡號");

        DsgOilCardStock cardStock = new DsgOilCardStock();
        cardStock.setOid(UUIDGenerator.getUUID());
        cardStock.setAppNo(card.getAppNo());
        cardStock.setOilCom(card.getOilCom());
        cardStock.setCardClassify(card.getCardClassify());
        cardStock.setCardType(card.getCardType());
        cardStock.setCardNo(card.getCardNo());
        cardStock.setStockStatus(DsgOilCardStock.STOCK_STATUS_IN);
        cardStock.setCardInTime(new Date());
        cardStock.setPeriodTime(card.getCardEndDate());
        cardStock.setCardFaceName(card.getCardFaceName());
        stockService.save(cardStock);
        LambdaUpdateWrapper<DsgApplyStatus> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(DsgApplyStatus::getCardId, card.getOid());
        DsgApplyStatus status = new DsgApplyStatus();
        status.setIsReturn(1);
        statusService.update(status, updateWrapper);
    }

    @PutMapping(value = "/caltexMapping")
    @ApiOperation("SC返咭 mapping caltex新申請/加車/補咭/轉油種 這個更能主要用於caltex的油咭與車牌mapping")
    public AjaxResult mapping(@ApiParam(required = true)@RequestParam String cardOid,
                              @ApiParam(required = true)@RequestParam String cardNo,
                              @ApiParam(required = true)@RequestParam String cardEndDate) throws Exception {
        Date date = DateUtil.parseDate(cardEndDate, "yyyy-MM-dd");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("CARD_NO", cardNo);
        wrapper.eq("PERIOD_TIME", date);
        wrapper.eq("ENT_CODE", getEntCode());
        DsgOilCardStock stock = stockService.getOne(wrapper);
        if (stock.getStockStatus() == DsgOilCardStock.STOCK_STATUS_IN)
            return fail("該咭已做過MAPPING");
        if (stock == null)
            return fail("該咭未做SC返咭上載excel或未做SC返咭拉咭確認或有效期不一致");
        if (stock.getStockStatus() == DsgOilCardStock.STOCK_STATUS_OUT)
            return fail("該咭已出咭");
        if (stock.getStockStatus() != DsgOilCardStock.STOCK_STATUS_CONFIRM)
            return fail("該咭未做SC返咭拉咭確認");

        DsgApplyCard card = service.getById(cardOid);
        card.setCardNo(cardNo);
        card.setCardEndDate(date);
        card.setCardInTime(new Date());
        card.setCardStatus(DsgApplyCard.CARD_STATUS_2);
        service.updateById(card);

        LambdaUpdateWrapper<DsgApplyStatus> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(DsgApplyStatus::getCardId, card.getOid());
        DsgApplyStatus status = new DsgApplyStatus();
        status.setIsReturn(1);
        statusService.update(status, updateWrapper);

        DsgApproveCase applyCase = caseService.getCase(WorkflowService3.NODE_RETURN_CARD, card.getAppNo());
        if (applyCase == null) {
            throw new Exception("无返卡CASE");
        }
        if (DsgApproveCase.Status.started.getCode().equals(applyCase.getStatus())) {
            engine.forward(applyCase);
        }
        stock.setStockStatus(DsgOilCardStock.STOCK_STATUS_IN);
        stock.setCardInTime(new Date());
        stock.setAppNo(card.getAppNo());
        stock.setOilCom(card.getOilCom());
        stock.setCardType(card.getCardType());
        stock.setCardClassify(card.getCardClassify());
        stockService.updateById(stock);
        return success();
    }

    /**
     * 查询咭列表（分页）
     *
     * @param dsgApplyCard
     * @return
     */
    @GetMapping(value = "/selectDsgApplyCard")
    @ApiOperation("查询咭列表（分页）")
    public AjaxResult selectDsgApplyCard(DsgApplyCard dsgApplyCard) {
        // 分頁
        Page page = getPage();
        String sort = getParameter("sort");
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtil.isEmpty(sort)) {
            orderItem.setColumn("c.CREATE_TIME");
            orderItem.setAsc(false);
            orderItemList.add(orderItem);
            page.setOrders(orderItemList);
        }
        dsgApplyCard.setEntCode(SingletonLoginUtils.getSystemEntCode());
        IPage<DsgApplyCard> dsgApplyCardIPage = service.selectDsgApplyCard(page, dsgApplyCard);
        // 格式要返回的数据
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, dsgApplyCardIPage.getRecords(), (int) page.getTotal());
        return ajaxResult;
    }
}
